package com.example.mybatislearning.config;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.Proxy;

/**
 * @author zhangfei
 * @date 2024/1/4 10:48
 **/
public class TestMapperFactoryBean<T> implements InitializingBean,FactoryBean<T> {

    private Class<T> mapperInterface;

    private boolean addToConfig = true;

    public TestMapperFactoryBean() {
        // intentionally empty
        System.out.println("TestMapperFactoryBean...");
    }

    public TestMapperFactoryBean(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;



    }

    @Override
    public T getObject() throws Exception {
        TestMapperProxy<T> proxy = new TestMapperProxy(null);
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface},proxy);
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    // ------------- mutators --------------

    /**
     * Sets the mapper interface of the MyBatis mapper
     *
     * @param mapperInterface
     *          class of the interface
     */
    public void setMapperInterface(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    /**
     * Return the mapper interface of the MyBatis mapper
     *
     * @return class of the interface
     */
    public Class<T> getMapperInterface() {
        return mapperInterface;
    }

    /**
     * If addToConfig is false the mapper will not be added to MyBatis. This means it must have been included in
     * mybatis-config.xml.
     * <p>
     * If it is true, the mapper will be added to MyBatis in the case it is not already registered.
     * <p>
     * By default addToConfig is true.
     *
     * @param addToConfig
     *          a flag that whether add mapper to MyBatis or not
     */
    public void setAddToConfig(boolean addToConfig) {
        this.addToConfig = addToConfig;
    }

    /**
     * Return the flag for addition into MyBatis config.
     *
     * @return true if the mapper will be added to MyBatis in the case it is not already registered.
     */
    public boolean isAddToConfig() {
        return addToConfig;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
